<template>
  <div class="page-content evacuation-map">
    <!-- 主要内容区 -->
    <div class="flex gap-6 contan">
      <!-- 地图编辑区 -->
      <el-card class="map-container flex-grow">
        <div class="relative w-full bg-gray-100 overflow-hidden">
          <!-- 添加报警按钮 -->
          <el-button
            type="danger"
            size="large"
            class="alarm-button"
            @click="handleAlarm"
            :loading="alarmLoading"
          >
            <i class="i-carbon-alarm mr-2"></i>
            一键报警
          </el-button>
         
          <div class="map-editor-canvas" ref="mapCanvas">
            <el-input
              v-model="content"
              placeholder="请输入标注内容"
              style="width: 200px"
              v-if="showInput"
              :style="{
                position: 'absolute',
                left: inputPosition.x + 'px',
                top: inputPosition.y + 'px',
                zIndex: 1000
              }"
            />
            <BMap
              :center="centerPoint"
              :zoom="16"
              enable-scroll-wheel-zoom
              @initd="handleInitd"
              ak="LVTvcupjBjlPmEDPNV2MbkhTXUCKnSQS"
            >
              <!-- 起点图标 -->
              <BMarker :zIndex="9999" :position="coordinates" icon="start" />
              <!-- 多个文本标注 -->
              <BLabel
                v-for="(item, index) in nodeOperationPath"
                :key="index"
                :content="item.text || ''"
                :position="{ lng: item.lng, lat: item.lat }"
                :enableMassClear="true"
                :style="{
                  color: '#78829D',
                  backgroundColor: '#fff',
                  border: '1px solid #E5E5E5',
                  borderRadius: '3px',
                  padding: '5px 10px',
                  fontSize: '12px',
                  zIndex: 1000
                }"
              />
            </BMap>
          </div>
        </div>
      </el-card>
      <!-- 右侧路线管理区 -->
      <el-card style="width: 300px">
        <template #header>
          <div class="flex justify-between items-center">
            <span>路线管理</span>
            <el-button type="primary" size="small" @click="addNewRoute">
              <i class="i-carbon-add mr-1"></i>新建路线
            </el-button>
            <el-button type="primary" size="small" @click="saveAccess"> 保存 </el-button>
          </div>
        </template>

        <div class="route-list">
          <el-empty v-if="routes.length === 0" description="暂无路线" />
          <div v-else class="space-y-3 overflow-y-auto max-h-[calc(-261px+100vh)]">
            <div
              v-for="(route, index) in routes"
              :key="index"
              class="route-item p-3 border rounded cursor-pointer"
              :class="{ 'border-primary bg-blue-50': route.isActive }"
              @click="selectRoute(route.id, index)"
            >
              <div class="flex justify-between items-center">
                <div class="flex items-center">
                  <div class="font-medium text-gray-500">{{ route.name }}</div>
                </div>
                <div class="flex gap-1">
                  <el-button size="small" text circle @click.stop="editRoute(route.id, index)">
                    <i class="i-carbon-edit"></i>
                  </el-button>
                  <el-button
                    size="small"
                    text
                    circle
                    type="danger"
                    @click.stop="deleteRoute(route.id, index)"
                  >
                    <i class="i-carbon-trash-can"></i>
                  </el-button>
                </div>
              </div>
              <div v-if="route.description" class="text-gray-500 text-xs mt-1">{{
                route.description
              }}</div>
              <div class="text-gray-400 text-xs mt-1">{{ route.points.length }}个点位</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 路线编辑对话框 -->
    <el-dialog
      v-model="routeDialogVisible"
      :title="currentRouteId ? '编辑路线' : '新建路线'"
      width="500px"
    >
      <el-form ref="editingRouteRef" :model="editingRoute" :rules="rules" label-width="80px">
        <el-form-item label="通道名称" prop="accessName">
          <el-input v-model="editingRoute.accessName" placeholder="请输入通道名称" />
        </el-form-item>
        <el-form-item label="注意事项" prop="attention">
          <el-input v-model="editingRoute.attention" placeholder="请输入注意事项" />
        </el-form-item>
      </el-form>
      <div class="flex justify-center gap-4">
        <el-button @click="cancelRoute(editingRouteRef)">取消</el-button>
        <el-button type="primary" @click="saveRoute(editingRouteRef)">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import type { EvacuationRoute } from '@/types/evacuation'
  import { PointType } from '@/types/evacuation'
  import {
    CoordinatesFromType,
    CoordinatesToType,
    usePointConvertor,
    usePointGeocoder,
    PointGeocoderResult
  } from 'vue3-baidu-map-gl'
  const { convert, result, isError } = usePointConvertor()
  const { get, result: AddressComponent } = usePointGeocoder<PointGeocoderResult>()
  import {
    scenicEscapeAccessSaveAccessUsingPost,
    scenicEscapeAccessPageAccessUsingPost,
    scenicEscapeAccessDeleteAccessByIdUsingPost,
    alarmUrgencyAlarmUsingPost
  } from '@/api/4a'
  import qidianIcon from '@/assets/img/map/qidian.png'
  import zhongdianIcon from '@/assets/img/map/zhongdian.png'
  import type { CoordinatePoint } from '@/types/EvacuationMap'
  const userStore = useUserStore()
  const userInfo = computed(() => userStore.getUserInfo)
  // 中心点坐标
  const centerPoint = ref({ lng: 114.178654, lat: 30.507036 })
  // 起点坐标
  const coordinates = ref({ lat: 39.915185, lng: 116.403901 })

  const mapCanvas = ref<HTMLDivElement | null>(null)

  // 在 script setup 顶部声明 BMapGL
  const BMapGL = ref<any>(null)
  const alarmLoading = ref(false)

  const scene = ref<any>(null)
  let PolylineEditvalue: any
  let PolylineDrawValue: any
  let polylineObj: any
  // 路线列表
  const routes = ref<EvacuationRoute[]>([])

  const allPoints = ref([])
  const allPointsEdit = ref([])

  // 添加一个数组来存储所有转换后的坐标点
  const convertedPoints = ref<CoordinatePoint[]>([])

  // 地图编辑操作
  const mapEditing = ref(false)

  // 当前选中的路线ID
  const currentRouteId = ref<number | null>(null)

  // 当前选中路线index
  const selectIndex = ref(0)

  // 是否删除路线
  const isDeleteRoute = ref(false)

  const editingRouteRef = ref<FormInstance>()

  const content = ref('')
  const nodeOperationPath = ref<Array<{ lng: number; lat: number; text: string }>>([])
  const nodeOperationIndex = ref<number>()
  const showInput = ref(false)
  const inputPosition = ref({ x: 0, y: 0 })
  // 线路表单验证
  const rules = reactive<FormRules>({
    accessName: [{ required: true, message: '请输入通道名称', trigger: 'blur' }],
    attention: [{ required: true, message: '请输入注意事项', trigger: 'blur' }]
  })

  // 定义 targetIterator 的接口
  interface TargetIterator {
    path: Array<{ lng: number; lat: number; text?: string }>
    index: number
    text?: string
  }

  let targetIterator: TargetIterator

  // 添加标记的函数
  const addMarkers = (targetMap: any, points: any[]) => {
    if (!points.length || !BMapGL.value) return
    // 清除已有的标记
    const overlays = targetMap.getOverlays()
    overlays.forEach((overlay: any) => {
      if (overlay instanceof BMapGL.value.Marker) {
        targetMap.removeOverlay(overlay)
      }
    })

    // 添加起点标记
    const startMarker = new BMapGL.value.Marker(points[0], {
      icon: new BMapGL.value.Icon(qidianIcon, new BMapGL.value.Size(40, 40), {
        imageOffset: new BMapGL.value.Size(0, 0), // 图标的偏移量
        anchor: new BMapGL.value.Size(20, 35)
      })
    })
    startMarker.setTitle('起点')
    targetMap.addOverlay(startMarker)

    // 添加终点标记
    if (points.length > 1) {
      const endMarker = new BMapGL.value.Marker(points[points.length - 1], {
        icon: new BMapGL.value.Icon(zhongdianIcon, new BMapGL.value.Size(40, 40), {
          imageOffset: new BMapGL.value.Size(0, 0),
          anchor: new BMapGL.value.Size(20, 35)
        })
      })
      endMarker.setTitle('终点')
      targetMap.addOverlay(endMarker)
    }
  }

  let polyline = ref({
    instance: null as any,
    isDrawing: true,
    toggle() {
      let _polyline = polyline.value
      if (_polyline.instance) {
        _polyline.isDrawing ? _polyline.instance.closeAll() : _polyline.instance.open()
        _polyline.isDrawing = !_polyline.isDrawing
      }
    }
  })
  let polylineEdit = ref({
    instance: null as any,
    isDrawing: true,
    toggle() {
      let _polyline = polylineEdit.value
      if (_polyline.instance) {
        _polyline.isDrawing ? _polyline.instance.closeAll() : _polyline.instance.open()
        _polyline.isDrawing = !_polyline.isDrawing
      }
    }
  })
  let clearFn = ref()

  // 获取点击位置的屏幕坐标
  const getScreenPosition = (map: any, lng: number, lat: number) => {
    const pixel = map.pointToOverlayPixel(new BMapGL.value.Point(lng, lat))
    return {
      x: pixel.x,
      y: pixel.y
    }
  }

  const handleInitd = ({ map, BMapGL: _BMapGL }: { map: any; BMapGL: any }) => {
    // 保存 BMapGL 引用
    BMapGL.value = _BMapGL

    // 添加地图事件监听
    map.addEventListener('zoomend', updateInputPosition)
    map.addEventListener('moveend', updateInputPosition)
    map.addEventListener('dragend', updateInputPosition)

    import('bmap-draw').then(
      ({ DrawScene, PolylineDraw, PolylineEdit, CorrectPoint, OperateEventType }) => {
        PolylineEditvalue = PolylineEdit
        PolylineDrawValue = PolylineDraw
        scene.value = new DrawScene(map)
        clearFn.value = () => {
          scene.value.clearData()
          if (polyline.value.instance) {
            // 清除所有覆盖物
            polyline.value.instance.scene.map.clearOverlays()
            // 重置 overlay
            polyline.value.instance.overlay = null
          }
        }
        // 折线绘制
        polyline.value.instance = new PolylineDraw(scene.value, {
          isOpen: false,
          isOnMap: true,
          enableSnap: false,
          isSelectDraw: false,
          isSeries: false,
          enableDragging: false,
          enableCalculate: true
          // limitPoint:10
        })
        loadRoutes()

        // 节点操作
        const polyLayer = new BMapGL.value.GeoJSONLayer('poly', {
          dataSource: null
        })
        map.addGeoJSONLayer(polyLayer)
        scene.value.instances = polyLayer.overlayData
        const correctPoint = new CorrectPoint(scene.value, true)
        correctPoint.addEventListener(OperateEventType.CLICK, (e: any) => {
          targetIterator = e.target
          // 如果 nodeOperationPath 为空，则初始化
          if (nodeOperationPath.value.length === 0) {
            nodeOperationPath.value = targetIterator.path.map((point: any) => ({
              lng: point.lng,
              lat: point.lat,
              text: ''
            }))
          }else{
            // 地图新增点，进行文本添加
            editingRouteData.value = JSON.stringify(nodeOperationPath.value)
            nodeOperationPath.value = targetIterator.path.map((point: any) => {
              // 在editingRouteData中查找匹配的点
              const existingPoint = JSON.parse(editingRouteData.value).find((op: any) => {
                const opLngStr = op.lng.toString().slice(0, 7)
                const opLatStr = op.lat.toString().slice(0, 7)
                const pointLngStr = point.lng.toString().slice(0, 7)
                const pointLatStr = point.lat.toString().slice(0, 7)
                return opLngStr === pointLngStr && opLatStr === pointLatStr
              })
              return {
                lng: point.lng,
                lat: point.lat,
                text: existingPoint && existingPoint.text != '' ? existingPoint.text : ''
              }
            })
          }
          nodeOperationIndex.value = targetIterator.index
          content.value = nodeOperationPath.value[targetIterator.index]?.text || ''
          // 获取点击坐标的屏幕位置
          const point = targetIterator.path[targetIterator.index]
          const position = getScreenPosition(scene.value.map, point.lng, point.lat)
          // 设置输入框位置并显示
          inputPosition.value = {
            x: position.x,
            y: position.y - 40 // 向上偏移40px，避免遮挡坐标点
          }
          showInput.value = true
        })

        // 报警地址解析
        get(scene.value?.map?.getCenter())
      }
    )
  }
  // 监听地图缩放和平移事件，更新输入框位置
  const updateInputPosition = () => {
    if (nodeOperationIndex.value !== undefined && showInput.value) {
      const point = nodeOperationPath.value[nodeOperationIndex.value]
      const position = getScreenPosition(scene.value.map, point.lng, point.lat)
      inputPosition.value = {
        x: position.x,
        y: position.y - 40
      }
    }
  }
  // 路线编辑对话框
  const routeDialogVisible = ref(false)
  const editingRoute = reactive({
    id: null as any,
    accessName: '',
    accessNameEn: '1',
    attention: '',
    accessLength: '0',
    accessImg: '0',
    plotJson: { coordinates: [] } as any,
    scenicServiceHotlineBoList: [{}]
  })
  const editingRouteData = ref<any>({})

  // 添加新路线
  const addNewRoute = () => {
    currentRouteId.value = null
    editingRoute.id = null
    editingRoute.accessName = ''
    editingRoute.attention = ''
    editingRoute.plotJson = { coordinates: [] }
    editingRoute.accessLength = '0'
    editingRoute.accessImg = '0'

    routeDialogVisible.value = true
  }

  // 选择路线
  const selectRoute = (id: number | null, index: number) => {
    // 如果当前路线未保存，提示用户
    if (
      routes.value[selectIndex.value]?.id === null &&
      isDeleteRoute.value == false &&
      index != selectIndex.value
    ) {
      ElMessageBox.confirm('当前路线未保存，切换路线将清空数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          nodeOperationPath.value = []
          nodeOperationIndex.value = undefined
          showInput.value = false
          inputPosition.value = { x: 0, y: 0 }
          setTimeout(() => {
            switchRoute(id, index)
          }, 0)
        })
        .catch(() => {
          // 用户取消切换，不做任何操作
        })
    } else {
      nodeOperationPath.value = []
      nodeOperationIndex.value = undefined
      showInput.value = false
      inputPosition.value = { x: 0, y: 0 }
      setTimeout(() => {
        switchRoute(id, index)
      }, 0)
    }
  }

  // 实际切换路线的逻辑
  const switchRoute = (id: number | null, index: number) => {
    isDeleteRoute.value = false
    // 清除现有的折线
    if (clearFn.value) {
      clearFn.value()
    }
    if (polyline.value.instance) {
      polyline.value.instance.overlay = null
    }
    // polyline.value.isDrawing = false
    selectIndex.value = index

    if (id == null) {
      routes.value.forEach((route) => (route.isActive = false))
      routes.value[index].isActive = true
      routes.value[index].plotJson = {}
      routes.value[index].id = null
      editingRoute.plotJson = routes.value[index].plotJson
      editingRoute.accessName = routes.value[index].name
      editingRoute.attention = routes.value[index].description || ''
      editingRoute.id = routes.value[index].id
    } else {
      const findIndex = routes.value.findIndex((route) => route.id === id)
      if (findIndex !== -1) {
        routes.value.forEach((route) => (route.isActive = false))
        routes.value[findIndex].isActive = true
        editingRoute.plotJson = routes.value[findIndex].plotJson
        editingRoute.accessName = routes.value[findIndex].name
        editingRoute.attention = routes.value[findIndex].description || ''
        if (id != null) {
          getAccessById(routes.value[findIndex])
        }
      }
    }
    if (
      editingRoute.plotJson.coordinates == undefined ||
      editingRoute.plotJson.coordinates.length == 0
    ) {
      if (polyline.value.instance && polyline.value.instance.open) {
        polyline.value.instance.open()
      }
    }
  }

  // 编辑路线
  const editRoute = (id: number | null) => {
    const route = routes.value.find((route) => route.id === id)
    if (route) {
      currentRouteId.value = id
      editingRoute.accessName = route.name
      editingRoute.attention = route.description || ''
      routeDialogVisible.value = true
    }
  }

  // 删除路线
  const deleteRoute = (id: number | null, index: number) => {
    ElMessageBox.confirm('确定要删除该路线吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        if (id == null) {
          routes.value.splice(index, 1)
          ElMessage.success('路线已删除')
          isDeleteRoute.value = true
          selectIndex.value = index - 1
          if (routes.value.length == 0) {
            // 清除现有的折线
            if (clearFn.value) {
              clearFn.value()
            }
          } else {
            if (selectIndex.value == -1) {
              selectRoute(routes.value[0].id, 0)
            } else {
              selectRoute(routes.value[selectIndex.value].id, selectIndex.value)
            }
          }
        } else {
          const index = routes.value.findIndex((route) => route.id === id)
          if (index !== -1) {
            try {
              scenicEscapeAccessDeleteAccessByIdUsingPost({ params: { accessId: id } }).then(
                (res) => {
                  if (res.code === 0) {
                    routes.value.splice(index, 1)
                    ElMessage.success('路线已删除')
                    isDeleteRoute.value = true
                    selectIndex.value = index - 1
                    if (routes.value.length == 0) {
                      // 清除现有的折线
                      if (clearFn.value) {
                        clearFn.value()
                      }
                    } else {
                      if (selectIndex.value == -1) {
                        selectRoute(routes.value[0].id, 0)
                      } else {
                        selectRoute(routes.value[selectIndex.value].id, selectIndex.value)
                      }
                    }
                  } else {
                    ElMessage.error(res.msg || '删除失败')
                  }
                }
              )
            } catch (error) {
              ElMessage.error('删除路线失败，请重试')
            }
          }
        }
      })
      .catch(() => {})
  }
  // 新增路线
  const saveRoute = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        if (currentRouteId.value) {
          // 更新现有路线
          const index = routes.value.findIndex((route) => route.id === currentRouteId.value)
          if (index !== -1) {
            routes.value[index].name = editingRoute.accessName
            routes.value[index].description = editingRoute.attention
            routes.value[index].updatedAt = new Date().toISOString()
            selectIndex.value = index
            ElMessage.success('路线已更新')
          }
        } else {
          // 添加新路线
          const newRoute: EvacuationRoute = {
            id: null,
            name: editingRoute.accessName,
            description: editingRoute.attention,
            points: [],
            color: '#409EFF',
            width: 4,
            isActive: true,
            createdAt: new Date().toISOString()
          }
          selectIndex.value = routes.value.length
          // 先取消所有路线的选中状态
          routes.value.forEach((route) => (route.isActive = false))
          // 添加新路线
          routes.value.push(newRoute)
          // // 清除现有的折线
          if (clearFn.value) {
            clearFn.value()
          }
          nodeOperationPath.value = []
          nodeOperationIndex.value = undefined
          showInput.value = false
          inputPosition.value = { x: 0, y: 0 }
          ElMessage.success('路线已创建')
        }
        routeDialogVisible.value = false
        mapEditing.value = true
        if (
          editingRoute.plotJson.coordinates == undefined ||
          editingRoute.plotJson.coordinates.length == 0
        ) {
          if (polyline.value.instance && polyline.value.instance.open) {
            polyline.value.instance.open()
          }
        }
      }
    })
  }
  // 取消路线名称
  const cancelRoute = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    routeDialogVisible.value = false
  }

  // 保存路线
  const saveAccess = () => {
    if (polyline.value.instance.overlay == null) {
      ElMessage.warning('请先绘制路线')
      return
    }
    if (editingRoute.id == null) {
      if (nodeOperationPath.value.length > 0) {
        polyline.value.instance.overlay.points = nodeOperationPath.value
        submitSaveAccess()
      } else {
        // 重置转换后的坐标点数组
        convertedPoints.value = []
        const points = polyline.value.instance.overlay.points.map((point: any) => {
          if (scene.value && scene.value.map) {
            allPoints.value = polyline.value.instance.overlay.points.map((p: any) => ({
              lng: p.lng,
              lat: p.lat
            }))
          }
        })
        // 将点分组,每10个一组
        for (let i = 0; i < allPoints.value.length; i += 10) {
          const pointsGroup = allPoints.value.slice(i, i + 10)
          convert(
            pointsGroup,
            CoordinatesFromType['COORDINATES_BD09_MC'],
            CoordinatesToType['COORDINATES_BD09']
          )
        }
      }
    } else {
      // if(nodeOperationPath.value.length > 0){
      //   polyline.value.instance.overlay.points = nodeOperationPath.value
      //   submitSaveAccess()
      // }else{
      // 重置转换后的坐标点数组
      convertedPoints.value = []
      const pointsEdit = polylineEdit.value.instance.overlay.points.map((point: any) => {
        if (scene.value && scene.value.map) {
          allPointsEdit.value = polylineEdit.value.instance.overlay.points.map((p: any) => ({
            lng: p.lng,
            lat: p.lat
          }))
        }
      })
      for (let i = 0; i < allPointsEdit.value.length; i += 10) {
        const pointsGroup = allPointsEdit.value.slice(i, i + 10)
        convert(
          pointsGroup,
          CoordinatesFromType['COORDINATES_BD09_MC'],
          CoordinatesToType['COORDINATES_BD09']
        )
      }
    }
    // }
  }
  const submitSaveAccess = () => {
    const coordinatePoints = polyline.value.instance.overlay.points.map((item: any) => [
      item.lng,
      item.lat
    ])
    editingRoute.plotJson = JSON.stringify({
      coordinates: coordinatePoints,
      points: polyline.value.instance.overlay.points
    })
    editingRoute.scenicServiceHotlineBoList = [
      {
        id: 1,
        serviceType: 1,
        serviceTypeId: 101,
        hotlineName: '景区客服热线',
        serviceTag: '123456789',
        serviceHotline: '95010',
        serviceDescribe: '提供景区相关咨询服务',
        openWeek: '(1)',
        openStartTime: '090000',
        openEndTime: '180000',
        serviceTime: 100,
        remark: '节假日正常开放'
      }
    ]

    scenicEscapeAccessSaveAccessUsingPost({ body: editingRoute as any })
      .then((res: any) => {
        if (res.code === 0) {
          ElMessage.success('保存成功')
          routes.value[selectIndex.value] = res.data
          routes.value[selectIndex.value].name = res.data.accessName
          routes.value[selectIndex.value].description = res.data.attention
          ;(routes.value[selectIndex.value].points = res.data.plotJson
            ? JSON.parse(res.data.plotJson).coordinates.map((coord: [number, number]) => ({
                x: coord[0],
                y: coord[1],
                type: PointType.MIDDLE
              }))
            : []),
            selectRoute(routes.value[selectIndex.value].id, selectIndex.value)
          // loadRoutes()
        } else {
          ElMessage.error(res.msg)
        }
      })
      .catch((error) => {
        ElMessage.error('保存失败')
      })
  }
  // 加载路线列表
  const loadRoutes = async () => {
    // 清除现有的线
    if (clearFn.value) {
      clearFn.value()
    }
    const res = await scenicEscapeAccessPageAccessUsingPost({ body: { size: 100, current: 1 } })
    if (res.code === 0 && res.data?.list) {
      routes.value = res.data.list.map((route) => ({
        id: route.id || 0,
        name: route.accessName || '',
        description: route.attention || '',
        points: route.plotJson
          ? JSON.parse(route.plotJson).coordinates.map((coord: [number, number]) => ({
              x: coord[0],
              y: coord[1],
              type: PointType.MIDDLE
            }))
          : [],
        color: '#409EFF',
        width: 4,
        isActive: false,
        createdAt: new Date().toISOString(),
        plotJson: route.plotJson
      }))

      if (routes.value.length > 0) {
        selectRoute(editingRoute.id || routes.value[0].id, 0)
        mapEditing.value = true
      } else {
        mapEditing.value = false
      }
    } else {
      ElMessage.error(res.msg || '加载路线失败')
    }
  }

  const getAccessById = (data: any) => {
    if (data) {
      Object.assign(editingRoute, data)
      const plotJsonData = JSON.parse(data.plotJson || '{"coordinates":[]}')
      editingRoute.plotJson = plotJsonData
      if (plotJsonData.points != undefined) {
        nodeOperationPath.value = plotJsonData.points
      } else {
        nodeOperationPath.value = []
      }
      // 清除现有的线
      if (clearFn.value) {
        clearFn.value()
      }
      // 如果有坐标点数据，则绘制在地图上
      if (plotJsonData.coordinates && plotJsonData.coordinates.length > 0 && BMapGL.value) {
        // // 创建坐标点数组
        const points = plotJsonData.coordinates.map((coord: [number, number]) => {
          return new BMapGL.value.Point(coord[0], coord[1])
        })

        // // 创建可编辑折线对象
        // polylineObj = new BMapGL.value.Polyline(points, {
        //   strokeColor: '#8055e3',
        //   strokeWeight: 4,
        //   strokeOpacity: 1,
        //   // enableEditing: true // 使折线可编辑
        // })
        // // 将折线添加到地图实例中
        // polyline.value.instance.scene.map.addOverlay(polylineObj)
        // 添加起点和终点标记
        addMarkers(polyline.value.instance.scene.map, points)
        polylineObj = new BMapGL.value.Polyline(points, {
          strokeColor: '#8055e3',
          strokeWeight: 4,
          strokeOpacity: 1
          // enableEditing: true // 使折线可编辑
        })
        scene.value.instances.push(polylineObj)
        polylineEdit.value.instance = new PolylineEditvalue(scene.value)
        polylineEdit.value.instance.scene.map.addOverlay(polylineObj)
        polylineEdit.value.instance.open(polylineObj)
        // polylineEdit.value.instance.addEventListener('operate-ok', e => {
        //     // 将点分组,每10个一组
        // // for (let i = 0; i < e.target.overlay.points?.length; i += 10) {
        // //   const pointsGroup =  e.target.overlay.points.slice(i, i + 10)
        // //   convert(
        // //     pointsGroup,
        // //     CoordinatesFromType['COORDINATES_BD09_MC'],
        // //     CoordinatesToType['COORDINATES_BD09']
        // //   )
        // // }
        //       // 清除起点和终点标记
        //   // addMarkers(polyline.value.instance.scene.map,e.target.points)
        // });
        // 保存到 polyline 实例中
        polyline.value.instance.overlay = {
          points: points.map((point: any) => ({
            latLng: {
              lng: point.lng,
              lat: point.lat
            }
          }))
        }
      }
    }
  }
  onMounted(() => {})

  // 修改watch函数来累积坐标点
  watch(
    () => result.value,
    (newValue) => {
      if (newValue && Array.isArray(newValue)) {
        // 将新转换的坐标点添加到累积数组中
        // convertedPoints.value = [...convertedPoints.value, ...newValue]
        const newPoints = newValue.map((point) => {
          // 查找nodeOperationPath中是否有相同坐标点
          const existingPoint = nodeOperationPath.value.find((op) => {
            const opLngStr = op.lng.toString().slice(0, 7)
            const opLatStr = op.lat.toString().slice(0, 7)
            const pointLngStr = point.lng.toString().slice(0, 7)
            const pointLatStr = point.lat.toString().slice(0, 7)
            return opLngStr === pointLngStr && opLatStr === pointLatStr
          })
          // 如果找到相同坐标点，保留其text值
          return existingPoint ? { ...point, text: existingPoint.text } : point
        })
        convertedPoints.value = [...convertedPoints.value, ...newPoints]

        // 检查是否所有点都已转换完成
        if (
          convertedPoints.value.length === allPoints.value.length ||
          convertedPoints.value.length === allPointsEdit.value.length
        ) {
          // 所有点都转换完成后，更新polyline的points
          polyline.value.instance.overlay.points = convertedPoints.value
          // 调用提交函数
          submitSaveAccess()
        }
      }
    }
  )

  watch(isError, (newValue) => {
    if (newValue) {
      ElMessage.error('坐标点绘制有误')
    }
  })

  // 监听输入框内容变化
  watch(content, (newValue) => {
    if (nodeOperationIndex.value !== undefined) {
      nodeOperationPath.value[nodeOperationIndex.value].text = newValue
    }
  })

  // 添加报警处理函数
  const handleAlarm = async () => {
    try {
      alarmLoading.value = true
      const currentPosition = scene.value?.map?.getCenter()
      const locationJson: any = {
        longitude: currentPosition.lng,
        latitude: currentPosition.lat
      }
      const alarmData = {
        location: AddressComponent.value?.address,
        locationJson: JSON.stringify(locationJson),
        locationParam: `type=drive&to=${AddressComponent.value?.address}&tocoord=${currentPosition.lat},${currentPosition.lng}&referer=YELBZ-3VZCM-HWI6T-6G7IO-T7RL2-O6BBB`,
        path: '/urgency-alarm/info',
        phone: userInfo.value.usrPhone,
        userId: userInfo.value.id
      }
      const res = await alarmUrgencyAlarmUsingPost({ body: alarmData })
      if (res.code === 0) {
        ElMessage.success('报警信息已发送')
      } else {
        ElMessage.error(res.msg || '报警失败')
      }
    } catch (error) {
      ElMessage.error('报警失败，请重试')
    } finally {
      alarmLoading.value = false
    }
  }
</script>

<style lang="scss" scoped>
  .contan {
    height: 100% !important;
  }

  :deep(.baidu-map-container),
  :deep(.baidu-map-container .bmap-container),
  :deep(.baidu-map-container .bmap-container > div) {
    height: 100% !important;
  }

  .evacuation-map {
    .map-container {
      .alarm-button {
        position: absolute;
        top: 20px;
        right: 20px;
        z-index: 1000;
        // padding: 12px 24px;
        font-size: 14px;
      }
      .map-editor-canvas {
        position: relative;
        width: 100%;
        height: calc(-191px + 100vh);
        overflow: hidden;

        /* 添加触摸事件处理 */
        touch-action: none;

        :deep(.BMap_mask) {
          touch-action: none;
        }

        :deep(.anchorBL) {
          display: none;
        }

        .map-background {
          position: absolute;
          width: 100%;
          height: 100%;
          object-fit: contain;
          transition: transform 0.3s ease;
          transform-origin: center;
        }

        .map-overlay {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          pointer-events: none;

          .active-path {
            stroke-dasharray: 5;
            animation: dash 10s linear infinite;
          }

          .point-marker {
            cursor: pointer;

            &:hover {
              filter: brightness(1.2);
            }
          }
        }
      }
    }

    .tool-group {
      min-width: 150px;
    }

    @keyframes dash {
      to {
        stroke-dashoffset: 1000;
      }
    }
  }
</style>
